<template>
<section>
  <!--工具条-->
  <el-col :span="24" class="toolbar" style="padding-bottom: 0px;">
    <el-form :inline="true">
      <el-form-item>
        <el-select v-model="value" :placeholder="$t('message.select')">
          <el-option
              v-for="item in coinType"
              :key="item.value"
              :label="item.label"
              :value="item.value">
          </el-option>
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" v-on:click="addRobot">{{$t('message.add-robot')}}</el-button>
        <el-button type="primary" v-on:click="addRobotTest" v-if="!isTest">一键添加机器人</el-button>
        <el-button type="primary" v-on:click="addRobotTest2" v-if="!isTest">一键添加机器人(小币种)</el-button>
      </el-form-item>
    </el-form>
  </el-col>

  <!--列表-->
  <el-table
      v-loading="dataTableVisible"
      :data="tableData"
      style="width: 100%">
    <el-table-column
        prop="robot_id"
        :label="$t('message.robot-id')" width="150">
    </el-table-column>
    <el-table-column
        prop="symbol"
        :label="$t('message.pair-name')" width="180">
    </el-table-column>
    <el-table-column
        prop="status"
        :label="$t('message.status')" width="150">
      <template slot-scope="scope">
        <span v-if="scope.row.status === '服务异常'">{{$t('message.service-exceptions')}}</span>
        <span v-else-if="scope.row.status === '开启'">{{$t('message.enabled')}}</span>
        <span v-else>{{$t('message.close')}}</span>
      </template>
    </el-table-column>
    <el-table-column
        prop="created_at"
        :label="$t('message.create-time')">
    </el-table-column>
    <el-table-column
        prop="detail"
        :label="$t('message.operation')">
      <template slot-scope="scope">
        <el-button @click="openDetail(scope.row.robot_id, scope.row.type, scope.row.symbol)" type="text" size="small">{{$t('message.detail')}}</el-button>
        <el-button @click="openRobotStart(scope.row.robot_id, scope.row.type, scope.row.status)" type="text" size="small">{{scope.row.status === '开启' ? $t('message.stop') : $t('message.open')}}</el-button>
        <el-button @click="openRobotDelete(scope.row.robot_id, scope.row.type)" type="text" size="small">{{$t('message.delete')}}</el-button>
        <el-button @click="openRobotOrderCancel(scope.row.robot_id, scope.row.type)" type="text" size="small">{{$t('message.revoke')}}</el-button>
        <el-button @click="openRobotAssets(scope.row.robot_id, scope.row.type)" type="text" size="small">{{$t('message.asset-details')}}</el-button>
        <el-button @click="openRobotShoot(scope.row.symbol)" type="text" size="small">{{$t('message.asset-snapshot')}}</el-button>
      </template>
    </el-table-column>
  </el-table>
  <!--主流币添加界面-->
  <el-dialog
      :title="$t('message.add-robot')"
      :visible.sync="addRobotMainVisible">
    <form :action="url" method="post" target="nm_iframe" enctype="multipart/form-data">
      <div class="dataTitle">{{$t('message.site-parameter-setting')}}</div>
      <table class="detailTable" border="1">
        <tr>
          <td>{{$t('message.site-secretKey')}}</td>
          <td>
            <input type="text" v-model="formData.selfSecretKey">
          </td>
          <td>{{$t('message.site-apiKey')}}</td>
          <td>
            <input type="text" v-model="formData.selfApiKey">
          </td>
        </tr>
        <tr>
          <td>{{$t('message.site-pairs')}}</td>
          <td>
            <el-select id="select" v-model="formData.selfSymbol" :placeholder="$t('message.select')">
              <el-option
                v-for="(item, idx) in symbols"
                :key="idx"
                :label="item"
                :value="item">
              </el-option>
            </el-select>
          </td>
          <td>{{$t('message.quantity-adjustment')}}</td>
          <td>
            <input type="text" v-model="formData.amountAdjust">
          </td>
        </tr>
        <tr>
          <td>{{$t('message.max-quantity-adjustment')}}</td>
          <td>
            <input type="text" v-model="formData.tradeAmountAdjustHigh">
          </td>
          <td>{{$t('message.minimal-quantity-adjustment')}}</td>
          <td>
            <input type="text" v-model="formData.tradeAmountAdjustLow">
          </td>
        </tr>
        <tr>
          <td>{{$t('message.bid-price-adjustment')}}</td>
          <td>
            <input type="text" v-model="formData.bidsPriceAdjust">
          </td>
          <td>{{$t('message.ask-price-adjustment')}}</td>
          <td>
            <input type="text" v-model="formData.asksPriceAdjust">
          </td>
        </tr>
        <tr>
          <td>{{$t('message.trade-limit')}}</td>
          <td>
            <input type="text" v-model="formData.tradeLimitSizePerMin">
          </td>
          <td>{{$t('message.max-order-quantity')}}</td>
          <td>
            <input type="text" v-model="formData.retainRecordsNum">
          </td>
        </tr>
        <tr>
          <td>{{$t('message.buyer-depth-ratio')}}</td>
          <td>
            <input type="text" v-model="formData.bidDepthRate">
          </td>
          <td>{{$t('message.seller-depth-ratio')}}</td>
          <td>
            <input type="text" v-model="formData.askDepthRate">
          </td>
        </tr>
        <tr>
          <td>{{$t('message.depth-synchronization-frequency')}}</td>
          <td>
            <!--<input type="text" v-model="formData.depthSyncFre" :disabled="!isEdit1">-->
            <el-select id="select" v-model="formData.depthSyncFre" :placeholder="$t('message.select')">
              <el-option
                v-for="(item, idx) in times"
                :key="idx"
                :label="item"
                :value="item">
              </el-option>
            </el-select>
          </td>
          <td>{{$t('message.number-of-depth-syncs')}}</td>
          <td>
            <!--<input type="text" v-model="formData.depthSyncNum" :disabled="!isEdit1">-->
            <el-select id="select" v-model="formData.depthSyncNum" :placeholder="$t('message.select')">
              <el-option
                v-for="(item, idx) in nums"
                :key="idx"
                :label="item"
                :value="item">
              </el-option>
            </el-select>
          </td>
        </tr>
        <tr>
          <td>{{$t('message.filtering-criteria')}}</td>
          <td>
            <input type="text" v-model="formData.hugeOrderLimit">
          </td>
          <td></td>
          <td></td>
        </tr>
      </table>
      <div class="dataTitle" style="margin-top: 20px">{{$t('message.interface-info')}}</div>
      <table class="detailTable" border="1">
        <tr>
          <td>{{$t('message.off-site-secretKey')}}</td>
          <td>
            <input type="text" v-model="formData.huobiSecretKey">
          </td>
          <td>{{$t('message.off-site-accessKeyId')}}</td>
          <td>
            <input type="text" v-model="formData.huobiAccessKeyId">
          </td>
        </tr>
        <tr>
          <td>{{$t('message.price-adjustment-rate')}}</td>
          <td>
            <input type="text" v-model="formData.priceAdjustRate">
          </td>
          <td>{{$t('message.connected-pair')}}</td>
          <td>
            <el-select id="select" v-model="formData.huobiSymbol" :placeholder="$t('message.select')">
              <el-option
                v-for="(item, idx) in to_symbols"
                :key="idx"
                :label="item"
                :value="item">
              </el-option>
            </el-select>
          </td>
        </tr>
        <tr>
          <td>{{$t('message.adjustment-frequency')}}</td>
          <td>
            <input type="text" v-model="formData.inspectTime">
          </td>
          <td></td>
          <td></td>
        </tr>
      </table>
      <div slot="footer" class="dialog-footer">
          <el-button type="primary" @click="submit"  :loading="addRobotLoading">{{$t('message.confirm')}}</el-button>
      </div>
    </form>
    <iframe id="id_iframe" name="nm_iframe" style="display:none;"></iframe>
  </el-dialog>
  <!--主流币详情-->
  <el-dialog
    :title="$t('message.major-coin-detail')"
    :visible.sync="robotMainDetailVisible"
    @closed="mainDetailClose">
    <div v-loading="mainDetailLoading">
      <table class="detailTable" border="1">
        <tr>
          <td>{{$t('message.site-secretKey')}}</td>
          <td>
            <input type="text" v-model="robotMainDetail.selfSecretKey" :disabled="!isEdit1">
          </td>
          <td>{{$t('message.site-apiKey')}}</td>
          <td>
            <input type="text" v-model="robotMainDetail.selfApiKey" :disabled="!isEdit1">
          </td>
        </tr>
        <tr>
          <td>{{$t('message.site-pairs')}}</td>
          <td>
            {{robotMainDetail.selfSymbol}}
          </td>
          <td>{{$t('message.quantity-adjustment')}}</td>
          <td>
            <input type="text" v-model="robotMainDetail.amountAdjust" :disabled="!isEdit1">
          </td>
        </tr>
        <tr>
          <td>{{$t('message.max-quantity-adjustment')}}</td>
          <td>
            <input type="text" v-model="robotMainDetail.tradeAmountAdjustHigh" :disabled="!isEdit1">
          </td>
          <td>{{$t('message.minimal-quantity-adjustment')}}</td>
          <td>
            <input type="text" v-model="robotMainDetail.tradeAmountAdjustLow" :disabled="!isEdit1">
          </td>
        </tr>
        <tr>
          <td>{{$t('message.bid-price-adjustment')}}</td>
          <td>
            <input type="text" v-model="robotMainDetail.bidsPriceAdjust" :disabled="!isEdit1">
          </td>
          <td>{{$t('message.ask-price-adjustment')}}</td>
          <td>
            <input type="text" v-model="robotMainDetail.asksPriceAdjust" :disabled="!isEdit1">
          </td>
        </tr>
        <tr>
          <td>{{$t('message.trade-limit')}}</td>
          <td>
            <input type="text" v-model="robotMainDetail.tradeLimitSizePerMin" :disabled="!isEdit1">
          </td>
          <td>{{$t('message.max-order-quantity')}}</td>
          <td>
            <input type="text" v-model="robotMainDetail.retainRecordsNum" :disabled="!isEdit1">
          </td>
        </tr>
        <tr>
          <td>{{$t('message.buyer-depth-ratio')}}</td>
          <td>
            <input type="text" v-model="robotMainDetail.bidDepthRate" :disabled="!isEdit1">
          </td>
          <td>{{$t('message.seller-depth-ratio')}}</td>
          <td>
            <input type="text" v-model="robotMainDetail.askDepthRate" :disabled="!isEdit1">
          </td>
        </tr>
        <tr>
          <td>{{$t('message.depth-synchronization-frequency')}}</td>
          <td>
            <!--<input type="text" v-model="formData.depthSyncFre" :disabled="!isEdit1">-->
            <el-select id="select"
                       v-model="robotMainDetail.depthSyncFre"
                       :placeholder="robotMainDetail.depthSyncFre + '分钟'"
                       :disabled="!isEdit1">
              <el-option
                v-for="(item, idx) in times"
                :key="idx"
                :label="item"
                :value="item">
              </el-option>
            </el-select>
          </td>
          <td>{{$t('message.number-of-depth-syncs')}}</td>
          <td>
            <!--<input type="text" v-model="formData.depth_sync_fre" :disabled="!isEdit1">-->
            <el-select id="select" v-model="robotMainDetail.depthSyncNum" :disabled="!isEdit1">
              <el-option
                v-for="(item, idx) in nums"
                :key="idx"
                :label="item"
                :value="item">
              </el-option>
            </el-select>
          </td>
        </tr>
        <tr>
          <td>{{$t('message.filtering-criteria')}}</td>
          <td>
            <input type="text" v-model="robotMainDetail.hugeOrderLimit" :disabled="!isEdit1">
          </td>
          <td></td>
          <td></td>
        </tr>
      </table>
      <div class="dataTitle" style="margin-top: 20px">{{$t('message.interface-info')}}</div>
      <table class="detailTable" border="1">
        <tr>
          <td>{{$t('message.off-site-secretKey')}}</td>
          <td>
            <input type="text" v-model="robotMainDetail.huobiSecretKey" :disabled="!isEdit1">
          </td>
          <td>{{$t('message.off-site-accessKeyId')}}</td>
          <td>
            <input type="text" v-model="robotMainDetail.huobiAccessKeyId" :disabled="!isEdit1">
          </td>
        </tr>
        <tr>
          <td>{{$t('message.price-adjustment-rate')}}</td>
          <td>
            <input type="text" v-model="robotMainDetail.priceAdjustRate" :disabled="!isEdit1">
          </td>
          <td>{{$t('message.connected-pair')}}</td>
          <td>
            {{robotMainDetail.huobiSymbol}}
          </td>
        </tr>
        <tr>
          <td>{{$t('message.adjustment-frequency')}}</td>
          <td>
            <input type="text" v-model="robotMainDetail.inspectTime" :disabled="!isEdit1">
          </td>
          <td></td>
          <td></td>
        </tr>
      </table>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" v-if="!isEdit1" @click="isEdit1 = true">{{$t('message.edit')}}</el-button>
        <el-button type="primary" v-else @click="editSubmit1" :loading="modifyRobotLoading">{{$t('message.confirm')}}</el-button>
        <el-button type="info" @click="robotMainDetailVisible = false">{{$t('message.cancel')}}</el-button>
      </div>
    </div>
  </el-dialog>
  <!--小币种币详情-->
  <el-dialog
    :title="$t('message.rare-coin-detail')"
    :visible.sync="robotRecDetailVisible"
    @closed="recDetailClose"
    width="80%"
    >
    <div v-loading="recDetailLoading">
      <div class="option-btns">
        <el-upload
          ref="upload"
          action="/wm/upload/"
          :show-file-list="false"
          :on-change="readExcel"
          :auto-upload="false">
          <el-button
            slot="trigger"
            icon="el-icon-upload2"
            size="small"
            type="primary">
            {{$t('message.import-model')}}
          </el-button>
        </el-upload>
        <el-button
          size="small"
          type="primary"
          v-on:click="downloadMater()">
          <i class="el-icon-download el-icon--right"></i>{{$t('message.export-model')}}
        </el-button>
      </div>
      <table class="detailTable detailTable2" border="1" >
        <tr>
          <td>{{$t('message.pair-name')}}</td>
          <td>
            {{recDetail.symbol}}
          </td>
          <td>{{$t('message.trade-limit-per-min')}}</td>
          <td>
            <input type="text" v-model.number="recDetail.trade_limit_size_per_min" :disabled="!isEdit2">
          </td>
          <td>{{$t('message.max-order-quantity')}}</td>
          <td>
            <input type="text" v-model.number="recDetail.retain_recods_num" :disabled="!isEdit2">
          </td>
        </tr>
      </table>
      <el-table
        :data="recDetail.dataTable"
        :cell-style="{textAlign: 'center'}"
        :header-cell-style="{textAlign: 'center'}"
        height="350"
        border
        style="width: 100%">
        <el-table-column
          prop="time"
          :label="$t('message.time')">
        </el-table-column>
        <el-table-column
          prop="bidsLow"
          :label="$t('message.minimal-bid-price')">
          <template slot-scope="scope">
            <input class="inp" type="text" v-model="scope.row.bidsLow" :disabled="!isEdit2">
          </template>
        </el-table-column>
        <el-table-column
          prop="bidsHigh"
          :label="$t('message.max-bid-price')">
          <template slot-scope="scope">
            <input class="inp" type="text" v-model="scope.row.bidsHigh" :disabled="!isEdit2">
          </template>
        </el-table-column>
        <el-table-column
          prop="asksLow"
          :label="$t('message.minimal-ask-price')">
          <template slot-scope="scope">
            <input class="inp" type="text" v-model="scope.row.asksLow" :disabled="!isEdit2">
          </template>
        </el-table-column>
        <el-table-column
          prop="asksHigh"
          :label="$t('message.max-ask-price')">
          <template slot-scope="scope">
            <input class="inp" type="text" v-model="scope.row.asksHigh" :disabled="!isEdit2">
          </template>
        </el-table-column>
        <el-table-column
          prop="open"
          :label="$t('message.opening-price')">
          <template slot-scope="scope">
            <input  class="inp" type="text" v-model="scope.row.open" :disabled="!isEdit2">
          </template>
        </el-table-column>
        <el-table-column
          prop="close"
          :label="$t('message.closing-price')">
          <template slot-scope="scope">
            <input  class="inp" type="text" v-model="scope.row.close" :disabled="!isEdit2">
          </template>
        </el-table-column>
        <el-table-column
          prop="amountHight"
          :label="$t('message.max-quantity')">
          <template slot-scope="scope">
            <input class="inp" type="text" v-model="scope.row.amountHight" :disabled="!isEdit2">
          </template>
        </el-table-column>
        <el-table-column
          prop="amountLow"
          :label="$t('message.minamal-quantity')">
          <template slot-scope="scope">
            <input class="inp" type="text" v-model="scope.row.amountLow" :disabled="!isEdit2">
          </template>
        </el-table-column>
        <el-table-column
          prop="depth"
          :label="$t('message.depth')">
          <template slot-scope="scope">
            <input class="inp" type="text" v-model="scope.row.depth" :disabled="!isEdit2">
          </template>
        </el-table-column>
        <el-table-column
          prop="frequency"
          :label="$t('message.quote-frequency')">
          <template slot-scope="scope">
            <input class="inp" type="text" v-model="scope.row.frequency" :disabled="!isEdit2">
          </template>
        </el-table-column>
      </el-table>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="autoEdit">{{$t('message.automatic-editing')}}</el-button>
        <el-button type="primary" v-if="!isEdit2" @click="isEdit2 = true">{{$t('message.manual-editing')}}</el-button>
        <el-button type="primary" v-else @click="editSubmit2" :loading="modifyRobotLoading2">{{$t('message.confirm')}}</el-button>
        <el-button type="info" @click="robotRecDetailVisible = false">{{$t('message.cancel')}}</el-button>
      </div>
    </div>
  </el-dialog>
  <!--机器人资金详情-->
  <el-dialog
    :title="$t('message.robot-asset-details')"
    :visible.sync="robotAssetsDetailVisible"
    width="60%">
    <el-table
      :data="assets"
      height="350"
      border
      style="width: 100%">
      <el-table-column
        prop="symbol"
        :label="$t('message.coin')">
      </el-table-column>
      <el-table-column
        prop="available"
        :label="$t('message.available-quantity')">
      </el-table-column>
      <el-table-column
        prop="freeze"
        :label="$t('message.frozen-quantity')">
      </el-table-column>
      <el-table-column
        prop="other_freeze"
        :label="$t('message.other-frozen')">
      </el-table-column>
      <el-table-column
        prop="recharge_status"
        :label="$t('message.recharge-status')">
        <template slot-scope="scope">
          <span>{{scope.row.recharge_status === 0 ? $t('message.no-recharge') : $t('message.rechargeable')}}</span>
        </template>
      </el-table-column>
      <el-table-column
        prop="withdraw_fee"
        :label="$t('message.withdrawal-fee')">
      </el-table-column>
      <el-table-column
        prop="withdraw_max"
        :label="$t('message.max-withdrawal-amount')">
      </el-table-column>
      <el-table-column
        prop="withdraw_min"
        :label="$t('message.minimal-withdrawal-amount')">
      </el-table-column>
      <el-table-column
        prop="withdraw_status"
        :label="$t('message.withdraw-status')">
        <template slot-scope="scope">
          <span>{{scope.row.withdraw_status === 0 ? $t('message.no-withdrawable') : $t('message.mentioning-currency')}}</span>
        </template>
      </el-table-column>
    </el-table>
    <div slot="footer" class="dialog-footer">
      <el-button type="primary" @click="robotAssetsDetailVisible = false">{{$t('message.close')}}</el-button>
    </div>
  </el-dialog>
  <!--机器人资金快照-->
  <el-dialog
    :title="$t('message.asset-snapshot')"
    :visible.sync="robotShootVisible"
    @closed="robotShootClose"
    width="90%">
    <div class="check-type" style="margin-bottom: 20px">
      <el-radio-group v-model="dateType" @change="changeDateType">
        <el-radio-button label="day"></el-radio-button>
        <el-radio-button label="week"></el-radio-button>
      </el-radio-group>
    </div>
    <snap-shoot-line></snap-shoot-line>
    <div slot="footer" class="dialog-footer">
      <el-button type="primary" @click="robotShootVisible = false">{{$t('message.close')}}</el-button>
    </div>
  </el-dialog>
  <!--自动编辑-->
  <el-dialog
    :title="$t('message.automatic-editing')"
    :visible.sync="autoEditVisible"
    @closed="autoEditClose">
    <div v-loading="autoEditLoading">
      <table class="detailTable" border="1">
        <tr>
          <td>{{$t('message.start-time')}}</td>
          <td>
            <el-date-picker
              v-model="autoEditList.startTime"
              type="datetime"
              placeholder="选择日期时间">
            </el-date-picker>
          </td>
          <td>{{$t('message.start-price')}}</td>
          <td>
            <input type="text" v-model="autoEditList.basePrice">
          </td>
        </tr>
        <tr>
          <td>{{$t('message.depth')}}</td>
          <td>
            <input type="text" v-model="autoEditList.depth">
          </td>
          <td>{{$t('message.quote-frequency')}}</td>
          <td>
            <input type="text" v-model="autoEditList.frequency">
          </td>
        </tr>
        <tr>
          <td>{{$t('message.minamal-quantity')}}</td>
          <td>
            <input type="text" v-model="autoEditList.amountLow">
          </td>
          <td>{{$t('message.max-quantity')}}</td>
          <td>
            <input type="text" v-model="autoEditList.amountHigh">
          </td>
        </tr>
        <tr>
          <td>卖方深度区间</td>
          <td>
            <input type="text" v-model="autoEditList.askDepthSec">
          </td>
          <td>买方深度区间</td>
          <td>
            <input type="text" v-model="autoEditList.bidDepthSec">
          </td>
        </tr>
        <tr>
          <td>{{$t('message.template-num')}}</td>
          <td>
            <el-select id="select" v-if="modelList" v-model="autoEditList.modelId" :placeholder="$t('message.select')">
              <el-option
                v-for="(item, idx) in modelList"
                :key="idx"
                :label="item.model_id"
                :value="item.model_id">
              </el-option>
            </el-select>
            <input v-else type="text" v-model="autoEditList.modelId">
          </td>
          <td>{{$t('message.time-interval')}}</td>
          <td>
            <el-select id="select" v-model="autoEditList.period" :placeholder="$t('message.select')">
              <el-option
                v-for="(item, idx) in [5, 15]"
                :key="idx"
                :label="item"
                :value="item">
              </el-option>
            </el-select>
          </td>
        </tr>
      </table>
      <div slot="footer" class="dialog-footer">
          <el-button type="primary" @click="setAutoEdit" :loading="setAutoEditLoading">{{$t('message.generate-data')}}</el-button>
      </div>
    </div>
  </el-dialog>
</section>
</template>

<script>
import url from 'common/js/http'
import { addRobot, addSecRobot, modifyRobot, robotList, majorSymbolList, robotDetail, robotStart, robotStop, robotDelete, robotOrderCancel, robotAssets, SetRobotData } from '../api/api'
import { haveEmpty, objValToString } from 'common/js/util'
import XLSX from 'xlsx'
import FileSaver from 'file-saver'
import {recDataTest, mainDataTest} from 'common/js/recRobotDataTest'
import SnapShootLine from 'components/snapShootLine'
import {mapActions, mapState} from 'vuex'

export default {
  data () {
    return {
      addRobotMainVisible: false,
      dataTableVisible: true,
      robotMainDetailVisible: false,
      robotRecDetailVisible: false,
      robotShootVisible: false,
      robotAssetsDetailVisible: false,
      autoEditVisible: false,
      addRobotLoading: false,
      modifyRobotLoading: false,
      modifyRobotLoading2: false,
      mainDetailLoading: false,
      recDetailLoading: false,
      autoEditLoading: false,
      setAutoEditLoading: false,
      isEdit1: false,
      isEdit2: false,
      checkedSybol: '',
      value: '',
      tableData: [
        {
          created_at: '',
          robot_id: '',
          status: '',
          symbol: '',
          type: ''
        }
      ],
      symbols: [],
      times: [1, 5, 10, 15, 20],
      nums: [5, 10, 20, 30],
      to_symbols: [],
      url: `${url}/robot/add`,
      formData: {
        amountAdjust: '',
        askDepthRate: '',
        asksPriceAdjust: '',
        bidDepthRate: '',
        bidsPriceAdjust: '',
        depthSyncFre: '',
        depthSyncNum: '',
        hugeOrderLimit: '',
        huobiAccessKeyId: '',
        huobiSecretKey: '',
        huobiSymbol: '',
        inspectTime: '',
        priceAdjustRate: '',
        retainRecordsNum: '',
        selfApiKey: '',
        selfSecretKey: '',
        selfSymbol: '',
        tradeAmountAdjustHigh: '',
        tradeAmountAdjustLow: '',
        tradeLimitSizePerMin: '',
        userName: JSON.parse(localStorage.getItem('userName'))
      },
      robotMainDetail: {
        name: '',
        robotId: 0,
        type: '',
        amountAdjust: 0,
        askDepthRate: 0,
        asksPriceAdjust: 0,
        bidDepthRate: 0,
        bidsPriceAdjust: 0,
        depthSyncFre: 0,
        depthSyncNum: 0,
        hugeOrderLimit: 0,
        huobiAccessKeyId: '',
        huobiSecretKey: '',
        huobiSymbol: '',
        inspectTime: 0,
        priceAdjustRate: 0,
        retainRecordsNum: 0,
        selfApiKey: '',
        selfSecretKey: '',
        selfSymbol: '',
        tradeAmountAdjustHigh: 0,
        tradeAmountAdjustLow: 0,
        tradeLimitSizePerMin: 0
      },
      recDetail: {},
      detailTitle: '',
      assets: [],
      dateType: 'day',
      autoEditList: {
        startTime: '',
        basePrice: '',
        depth: '',
        frequency: '',
        amountLow: '',
        amountHigh: '',
        askDepthSec: '',
        bidDepthSec: '',
        modelId: '',
        period: ''
      },
      modelList: []
    }
  },
  created () {
    robotList().then((res) => {
      console.log(res)
      if (res.data.code && res.data.code !== 0) {
        this.$message.error(res.data.error)
        return
      }
      this.tableData = res.data.robots
      this.dataTableVisible = false
    }).catch(() => {
      this.$message.error(this.$t('message.tip-10'))
    })
    majorSymbolList().then((res) => {
      console.log(res)
      if (res.data.code && res.data.code !== 0) {
        return
      }
      this.symbols = res.data.symbols
      this.to_symbols = res.data.to_symbols
    }).catch((err) => {
      console.log(err)
    })
  },
  beforeMount () {
    this.setModelList().then((res) => {
      console.log(res)
      this.modelList = res || []
    }).catch(() => {
      this.$message.error(this.$t('message.tip-11'))
    })
  },
  methods: {
    ...mapActions(['acSnapShoot', 'setRobotId', 'setModelList']),
    addRobot () {
      if (this.value === '1') {
        this.addRobotMainVisible = true
      } else if (this.value === '2') {
        this.$router.replace('/addRobot')
      } else {
        this.$message.error(this.$t('message.tip-12'))
      }
      console.log(this.symbols)
    },
    submitData (t, editRobot) {
      // 添加机器人1 编辑机器人为2，loading状态， 发送请求api
      // 1, this.addRobotLoading, this.addRobotMainVisible, addRobot
      t === 1 ? this.addRobotLoading = true : this.modifyRobotLoading = true
      // loading = true
      let formData = new FormData()
      let data = t === 1 ? this.formData : this.robotMainDetail
      for (let key in data) {
        formData.append(key, data[key])
      }
      if (t === 2) {
        formData.append('robotId', this.robotMainDetail.robotId)
        formData.append('type', this.robotMainDetail.type)
        console.log(formData)
      }
      editRobot(formData).then((res) => {
        t === 1 ? this.addRobotLoading = false : this.modifyRobotLoading = false
        if (res.data.code && res.data.code !== 0) {
          this.$message.error(res.data.error)
        } else {
          t === 1 ? this.addRobotMainVisible = false : this.robotMainDetailVisible = false
          if (t === 1) {
            this.formData = {
              amountAdjust: '',
              askDepthRate: '',
              asksPriceAdjust: '',
              bidDepthRate: '',
              bidsPriceAdjust: '',
              depthSyncFre: '',
              depthSyncNum: '',
              hugeOrderLimit: '',
              huobiAccessKeyId: '',
              huobiSecretKey: '',
              huobiSymbol: '',
              inspectTime: '',
              priceAdjustRate: '',
              retainRecordsNum: '',
              selfApiKey: '',
              selfSecretKey: '',
              selfSymbol: '',
              tradeAmountAdjustHigh: '',
              tradeAmountAdjustLow: '',
              tradeLimitSizePerMin: '',
              userName: JSON.parse(localStorage.getItem('userName'))
            }
            this.refreshRobotList()
            this.$message({
              message: this.$t('message.tip-13'),
              type: 'success'
            })
          } else {
            this.refreshRobotList()
            this.$message({
              message: this.$t('message.tip-14'),
              type: 'success'
            })
          }
        }
      }).catch(() => {
        this.$message.error('操作失败')
      })
    },
    submit () {
      if (!haveEmpty(this.formData)) {
        this.$message.error(this.$t('message.tip-15'))
      } else {
        if (parseFloat(this.formData.bidsPriceAdjust) < -0.05 || parseFloat(this.formData.bidsPriceAdjust) > 0) {
          this.$message.error('买价违规')
        } else if (parseFloat(this.formData.asksPriceAdjust) < 0 || parseFloat(this.formData.asksPriceAdjust) > 0.05) {
          this.$message.error('卖价违规')
        } else {
          this.$confirm(this.$t('message.tip-49'), this.$t('message.notification'), {
            confirmButtonText: this.$t('message.confirm'),
            cancelButtonText: this.$t('message.cancel'),
            type: 'warning'
          }).then(() => {
            this.submitData(1, addRobot)
          }).catch(() => {
            return false
          })
        }
      }
    },
    openDetail (id, type, name) {
      this.setRobotId(id)
      this.robotId = id
      if (type === '1') {
        this.robotMainDetailVisible = true
        this.mainDetailLoading = true
      } else {
        this.setModelList()
        this.robotRecDetailVisible = true
        this.recDetailLoading = true
      }
      let param = {robotId: id, type: type}
      robotDetail(param).then((res) => {
        console.log(res)
        if (res.data.code === 0) {
          this.detailTitle = name
          if (type === '1') {
            let robotDetailArr = res.data.robot
            this.robotMainDetail = robotDetailArr
            this.mainDetailLoading = false
          } else {
            let robotDetailArrs = res.data.robot
            let robotDetails = JSON.parse(robotDetailArrs.data_table)
            console.log(robotDetailArrs)
            this.recDetail = robotDetails.secRobot
            // this.recDetail.secRobot['robot_id'] = robotDetailArrs.robot_id
            // this.recDetail.secRobot['type'] = robotDetailArrs.type
            this.$set(this.recDetail, 'robot_id', robotDetailArrs.robot_id)
            this.$set(this.recDetail, 'type', robotDetailArrs.type)
            console.log(this.recDetail)
            this.recDetailLoading = false
          }
        }
      }).catch((err) => {
        console.log(err)
        this.$message.error(this.$t('message.tip-17'))
      })
    },
    openRobotStart (id, type, status) {
      let param = {robotId: id, type: type}
      if (status === '开启') {
        this.$confirm(this.$t('message.tip-18'), this.$t('message.notification'), {
          confirmButtonText: this.$t('message.confirm'),
          cancelButtonText: this.$t('message.cancel'),
          type: 'warning'
        }).then(() => {
          robotStop(param).then((res) => {
            console.log(res)
            if (res.data.code === 0) {
              this.refreshRobotList()
              this.$message({
                type: 'success',
                message: this.$t('message.tip-19')
              })
            } else {
              this.$message({
                type: 'error',
                message: res.data.error
              })
            }
          })
        }).catch(() => {
          this.$message({
            type: 'info',
            message: this.$t('message.tip-20')
          })
        })
      } else {
        this.$confirm(this.$t('message.tip-21'), this.$t('message.notification'), {
          confirmButtonText: this.$t('message.confirm'),
          cancelButtonText: this.$t('message.cancel'),
          type: 'warning'
        }).then(() => {
          robotStart(param).then((res) => {
            console.log(res)
            if (res.data.code === 0) {
              this.refreshRobotList()
              this.$message({
                type: 'success',
                message: this.$t('message.tip-3')
              })
            } else {
              this.$message({
                type: 'error',
                message: res.data.error
              })
            }
          })
        }).catch(() => {
          this.$message({
            type: 'info',
            message: this.$t('message.tip-4')
          })
        })
      }
    },
    openRobotDelete (id, type) {
      let param = {robotId: id, type: type}
      this.$confirm(this.$t('message.tip-22'), this.$t('message.notification'), {
        confirmButtonText: this.$t('message.confirm'),
        cancelButtonText: this.$t('message.cancel'),
        type: 'warning'
      }).then(() => {
        robotDelete(param).then((res) => {
          console.log(res)
          if (res.data.code === 0) {
            this.refreshRobotList()
            this.$message({
              type: 'success',
              message: this.$t('message.tip-5')
            })
          }
        })
      }).catch(() => {
        this.$message({
          type: 'info',
          message: this.$t('message.tip-4')
        })
      })
    },
    openRobotOrderCancel (id, type) {
      let param = {robotId: id, type: type}
      this.$confirm(this.$t('message.tip-6'), this.$t('message.notification'), {
        confirmButtonText: this.$t('message.confirm'),
        cancelButtonText: this.$t('message.cancel'),
        type: 'warning'
      }).then(() => {
        robotOrderCancel(param).then((res) => {
          console.log(res)
          if (res.data.code === 0) {
            this.refreshRobotList()
            this.$message({
              type: 'success',
              message: this.$t('message.tip-8')
            })
          }
        }).catch(() => {
          this.$message({
            type: 'error',
            message: this.$t('message.tip-23')
          })
        })
      }).catch(() => {
        this.$message({
          type: 'info',
          message: this.$t('message.tip-7')
        })
      })
    },
    openRobotAssets (id, type) {
      let param = {robotId: id, type: type}
      this.robotAssetsDetailVisible = true
      robotAssets(param).then((res) => {
        console.log(res)
        if (res.data.code === 0) {
          let obj = JSON.parse(res.data.user_assets)
          let arrTemp = obj.result
          let arr = []
          for (let idx in arrTemp) {
            console.log(idx)
            if (idx !== 'user_id') {
              arrTemp[idx].symbol = idx
              arr.push(arrTemp[idx])
            }
          }
          console.log(arr)
          this.assets = arr
        }
      })
    },
    openRobotShoot (symbol) {
      this.robotShootVisible = true
      this.checkedSybol = symbol
      let nowDate = new Date()
      let end = Date.parse(nowDate) / 1000
      let start = end - 24 * 3600
      let param = {selfSymbol: symbol, type: this.dateType, startTime: start, endTime: end}
      this.acSnapShoot({param, day: 'day'})
    },
    robotShootClose () {
      this.dateType = 'day'
    },
    changeDateType (val) {
      // console.log(val)
      let nowDate = new Date()
      let end = Date.parse(nowDate) / 1000
      // let start = new Date(nowDate - 7 * 24 * 3600 * 1000).getTime() / 1000
      let start = val === 'day' ? end - 24 * 3600 : end - 7 * 24 * 3600
      // let start = end - 7 * 24 * 3600
      let param = {selfSymbol: this.checkedSybol, type: val, startTime: start, endTime: end}
      this.acSnapShoot({param, val})
    },
    refreshRobotList () {
      this.dataTableVisible = true
      robotList().then((res) => {
        console.log(res)
        if (res.data.code && res.data.code !== 0) {
          this.$message.error(this.$t('message.tip-10'))
          return
        }
        this.tableData = res.data.robots
        this.dataTableVisible = false
      }).catch(() => {
        this.$message.error(this.$t('message.tip-10'))
      })
    },
    mainDetailClose () {
      console.log('主流币详情关闭')
      this.isEdit1 = false
    },
    recDetailClose () {
      console.log('小币种详情关闭')
      this.isEdit2 = false
    },
    editSubmit1 () {
      if (
        !haveEmpty(this.robotMainDetail)
      ) {
        this.$message.error(this.$t('message.tip-15'))
      } else {
        if (this.formData.bidsPriceAdjust !== this.formData.asksPriceAdjust) {
          this.$confirm(this.$t('message.tip-24'), this.$t('message.notification'), {
            confirmButtonText: this.$t('message.confirm'),
            cancelButtonText: this.$t('message.cancel'),
            type: 'warning'
          }).then(() => {
            this.submitData(2, modifyRobot)
          }).catch(() => {
            return false
          })
        } else {
          this.submitData(2, modifyRobot)
        }
      }
    },
    editSubmit2 () {
      this.modifyRobotLoading2 = true
      this.recDetail.robot_id = this.robotId
      let data = {
        secRobot: this.recDetail
      }
      modifyRobot(data).then((res) => {
        console.log(res)
        if (res.data.code !== 0) {
          this.modifyRobotLoading2 = false
          this.$message({
            type: 'error',
            message: res.data.error
          })
        } else {
          this.refreshRobotList()
          this.modifyRobotLoading2 = false
          this.robotRecDetailVisible = false
          this.$message({
            type: 'success',
            message: this.$t('message.tip-14')
          })
        }
      }).catch(() => {
        this.$message({
          type: 'error',
          message: this.$t('message.tip-17')
        })
      })
    },
    autoEdit () {
      this.robotRecDetailVisible = false
      this.autoEditVisible = true
    },
    setAutoEdit () {
      let list = this.autoEditList
      if (list.startTime === '' &&
        list.basePrice === '' &&
        list.depth === '' &&
        list.frequency === '' &&
        list.amountLow === '' &&
        list.amountHigh === '' &&
        list.modelId === '' &&
        list.period === '') {
        this.$message.error(this.$t('message.tip-15'))
      } else {
        let startTime = list.startTime
        list.startTime = (new Date(startTime).getTime() / 1000) + ''
        list.robotId = this.robot_id
        this.setAutoEditLoading = true
        SetRobotData(list).then(res => {
          console.log(res)
          this.setAutoEditLoading = false
          if (res.data.code !== 0) {
            res.data.error ? this.$message.error(res.data.error)
              : this.$message.error(this.$t('message.tip-26'))
          } else {
            this.recDetail = JSON.parse(res.data.data)['secRobot']
            this.autoEditVisible = false
            this.robotRecDetailVisible = true
            this.isEdit2 = true
          }
        })
      }
    },
    autoEditClose () {
      this.setAutoEditLoading = false
    },
    readExcel (file) {
      this.recDetailLoading = true
      const fileReader = new FileReader()
      fileReader.onload = (ev) => {
        try {
          const data = ev.target.result
          const workbook = XLSX.read(data, {
            type: 'binary'
          })
          for (let sheet in workbook.Sheets) {
            const sheetArray = XLSX.utils.sheet_to_json(workbook.Sheets[sheet])
            console.log(sheetArray)
            this.recDetail.dataTable = objValToString(sheetArray)
          }
        } catch (e) {
          this.$message.warning('文件类型不正确！')
          return false
        }
      }
      fileReader.readAsBinaryString(file.raw)
      this.recDetailLoading = false
      this.isEdit2 = true
    },
    downloadMater () {
      const defaultCellStyle = {
        font: { name: 'Times New Roman',
          sz: 16,
          color: { rgb: '#FF000000' },
          bold: false,
          italic: false,
          underline: false
        },
        alignment: { vertical: 'center', horizontal: 'center', indent: 0, wrapText: true },
        border: {
          top: { style: 'thin', color: { 'auto': 1 } },
          right: { style: 'thin', color: { 'auto': 1 } },
          bottom: { style: 'thin', color: { 'auto': 1 } },
          left: { style: 'thin', color: { 'auto': 1 } } }
      }
      const wopts = {bookType: 'xlsx', bookSST: false, type: 'binary', defaultCellStyle: defaultCellStyle, showGridLines: false}
      const wb = { SheetNames: ['Sheet1'], Sheets: {}, Props: {} }
      let data = this.recDetail.dataTable
      wb.Sheets['Sheet1'] = XLSX.utils.json_to_sheet(data)

      // 创建二进制对象写入转换好的字节流
      let tmpDown = new Blob([this.s2ab(XLSX.write(wb, wopts))], { type: 'application/octet-stream' })
      FileSaver.saveAs(tmpDown, this.recDetail.symbol + '.xlsx')
    },
    s2ab (s) {
      if (typeof ArrayBuffer !== 'undefined') {
        let buf = new ArrayBuffer(s.length)
        var view = new Uint8Array(buf)
        for (let i = 0; i !== s.length; ++i) view[i] = s.charCodeAt(i) & 0xFF
        return buf
      } else {
        let buf = new Array(s.length)
        for (let i = 0; i !== s.length; ++i) buf[i] = s.charCodeAt(i) & 0xFF
        return buf
      }
    },
    addRobotTest () {
      let formData = new FormData()
      let data = mainDataTest
      for (let key in data) {
        formData.append(key, data[key])
      }
      addRobot(formData).then((res) => {
        if (res.data.code && res.data.code !== 0) {
          this.$message.error(res.data.error)
        } else {
          this.refreshRobotList()
          this.$message({
            message: '添加成功',
            type: 'success'
          })
        }
      }).catch(() => {
        this.$message.error('操作失败')
      })
    },
    addRobotTest2 () {
      addSecRobot(recDataTest).then((res) => {
        console.log(res)
        if (res.data.code !== 0) {
          this.$message({
            type: 'error',
            message: res.data.error
          })
        } else {
          this.refreshRobotList()
          this.$message({
            type: 'success',
            message: '添加成功'
          })
        }
      }).catch(() => {
        this.$message({
          type: 'error',
          message: '添加失败'
        })
      })
    }
  },
  computed: {
    ...mapState(['robot_id']),
    isTest () {
      return window.location.hostname === '47.91.238.88'
    },
    userLevel () {
      return localStorage.getItem('userLevel')
    },
    coinType () {
      const all = [{
        value: '1',
        label: this.$t('message.major-coin')
      }, {
        value: '2',
        label: this.$t('message.rare-coin')
      }]
      return all.filter((item) => this.userLevel.indexOf(item.value) !== -1)
    }
  },
  components: {
    SnapShootLine
  }
}

</script>

<style scoped lang="scss">
  .dataTitle {
    margin: 10px auto;
    width: 600px;
  }
  .detailTable {
    margin: auto;
    width: 601px;
    border-collapse:collapse;
    border: 1px solid #dfe6ec;
    tr {
      td {
        overflow: hidden;
        word-break:break-all;
        width: 150px;
        height: 40px;
        padding: 5px;
        border: 1px solid #dfe6ec;
        text-align: center;
        span {
          font-size: 12px;
        }
        input {
          text-align: center;
          padding: 0 5px;
          width: 150px;
          height: 40px;
          border: none;
          &:disabled {
            background: #fff;
          }
        }
      }
      td:nth-child(1), td:nth-child(3), td:nth-child(5) {
        background: #eef1f6;
      }
    }
  }
  .detailTable2 {
    width: 100%;
    margin: 0 0 10px 0;
  }
  .dialog-footer {
    text-align: center;
    padding: 20px 50px 0 0;
  }
  .inp {
    text-align: center;
    padding: 0 5px;
    width: 75px;
    height: 40px;
    border: none;
    &:disabled {
      background: #fff;
    }
  }
  .option-btns {
    display: flex;
    justify-content: flex-end;
    button {
      margin: 10px 10px;
    }
  }
</style>
